//
//  CZXMPPRoomManager.m
//  CZWeiXin
//
//  Created by Alvechen on 16/4/13.
//  Copyright © 2016年 alvechen. All rights reserved.
//

#import "CZXMPPRoomManager.h"



@interface CZXMPPRoomManager ()<XMPPRoomDelegate>


/// key:房间jidStr    value:房间对象(XMPPRoom)
@property (nonatomic,strong) NSMutableDictionary  *rooms;

@end

@implementation CZXMPPRoomManager

+ (instancetype)shareInstance{
    
    static CZXMPPRoomManager *instance = nil;
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        
        instance = [self new];
    });
    
    return instance;
}

- (NSMutableDictionary *)rooms{
    
    if (_rooms != nil) {
        return _rooms;
    }
    //实例化
    _rooms = [NSMutableDictionary dictionary];
    
    return _rooms;
}

/**
 * 根据房间jid,加入或者创建该房间,并且指定我在房间里使用的昵称
 */
- (void)joinRoCreateRoomWithJid:(XMPPJID *)roomJid nickName:(NSString *)nickName{

    //先从字典里看房间存不存在
    XMPPRoom *room = self.rooms[roomJid.bare];
    
    if (!room) {
        
        //1.生成
        //2.配置
        //3.激活
        
        //创建房间
        //1.生成
        XMPPRoomCoreDataStorage *storage = [XMPPRoomCoreDataStorage sharedInstance];
        room = [[XMPPRoom alloc] initWithRoomStorage:storage jid:roomJid dispatchQueue:dispatch_get_main_queue()];
        //代理
        [room addDelegate:self delegateQueue:dispatch_get_main_queue()];
        //2.配置-无需配置
        
        //3.激活
        [room activate:[CZXMPPManager shareInstance].xmppStream];
        
        //保存到字典  key:房间jid字符串  value:房间对象
        self.rooms[roomJid.bare] = room;
    }
    
    
    //加入房间 指定要使用的昵称  以及是否要获取历史聊天记录
    //如果服务器上没有该JID的房间,服务器会帮我们创建
    [room joinRoomUsingNickname:nickName history:nil];

}

#pragma mark - XMPPRoomDelegate
/**
 * 房间创建成功
 
 你是房间的主人,有些事情要做:
 1.配置房间(必须),不配置无法使用
 2.邀请别人来房间聊天(可选)
 
 */
- (void)xmppRoomDidCreate:(XMPPRoom *)room{

    //1.配置房间-nil:使用默认配置
    [room configureRoomUsingOptions:nil];
    
    //2.邀请人来聊天
    [room inviteUser:[XMPPJID jidWithUser:@"lisi" domain:kCZ_DOMAIN resource:nil] withMessage:@"你来呀! 这里下红包雨!!"];
    
    [room inviteUser:[XMPPJID jidWithUser:@"u1" domain:kCZ_DOMAIN resource:nil] withMessage:@"你来呀! 这里下红包雨!!"];
    
}










@end
